package com.itheima.app.interceptor;

import cn.hutool.core.util.StrUtil;
import com.itheima.utils.ConstantUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class MovementInterceptor implements HandlerInterceptor {//发布动态拦截器

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        String method = request.getMethod();
        //System.out.println(method);
        if (StrUtil.equals("GET", method)) {//放行查询动态路径
            return true;
        }


        //1.获取用户id
        Long userId = UserHolder.getId();
        //2.查看是否冻结
        Boolean timeFlag = stringRedisTemplate.hasKey(StrUtil.format(ConstantUtil.FREEZE_TIME, userId));
        if (timeFlag) {
            //3.查看冻结范围
            String range = stringRedisTemplate.opsForValue().get(StrUtil.format(ConstantUtil.FREEZE_Range, userId));
            if (StrUtil.equals("3", range)) { //冻结发布动态
                //throw new BusinessException("冻结发布动态");
                //response.setStatus(405);
                return false;
            }

        }
        return true;

    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {



    }
}
